/*
 * JSUtil.java
 *
 * Created on December 20, 2004, 8:01 PM
 */

package jm.lib.web.util;

/**
 * Client/Browser side javascript utility
 * @author Jiming Liu
 */
public final class JSUtil {
    /**
     * Turn special characters into escaped characters conforming to JavaScript.
     * replace '"' to '\"', '\r' to '', '\n' to '\\n', '\t' to '\\t', '\' to '\\', ' to '\''
     * @param s
     * @return
     */
    public static String JSEscape(String s){
        int len = s.length();
        int pos = -1;
        
        SearchChar:for(int i = 0; i < len; i++){
            switch(s.charAt(i)){
                case '"':
                case '\r':
                case '\n':
                case '\t':
                case '\\':
                case '\'':
                    pos = i;
                    break SearchChar;
            }
        }
        
        if(pos == -1) return s;
        StringBuilder sb = new StringBuilder(len + len>>3);
        sb.append(s.substring(0, pos));
        for(int i = pos; i < len; i++){
            char a = s.charAt(i);
            switch(a){
                case '"':
                case '\\':
                case '\'':
                    sb.append(s.substring(pos, i));
                    pos = i+1;
                    sb.append('\\').append(a);
                    break;
                case '\n':
                    sb.append(s.substring(pos, i));
                    pos = i+1;
                    sb.append("\\n");
                    break;
                case '\t':
                    sb.append(s.substring(pos, i));
                    pos = i+1;
                    sb.append("\\t");
                    break;
                case '\r':
                    sb.append(s.substring(pos, i));
                    pos = i+1;
                    break;
            }
        }
        sb.append(s.substring(pos));
        return sb.toString();
    }
    
}
